import { Observable, Subscriber } from 'rxjs'
import {
  exec,
  execFile,
  ExecFileOptionsWithBufferEncoding,
  fork,
  ForkOptions,
  ChildProcess,
  spawn,
  SpawnOptions
} from 'child_process'
import { Injectable } from '@nestjs/common'
@Injectable()
export class ChildProcesService {
  exec(command: string): Observable<{ stdout: string; stderr: string }> {
    return Observable.create((obser: Subscriber<any>) => {
      exec(command, (error: Error | null, stdout: string, stderr: string) => {
        if (error) {
          obser.error(error)
        }
        obser.next({
          stdout,
          stderr
        })
      })
    })
  }

  execFile(
    file: string,
    options: ExecFileOptionsWithBufferEncoding
  ): Observable<{ stdout: Buffer; stderr: Buffer }> {
    return Observable.create((obser: Subscriber<any>) => {
      execFile(file, options, (error: Error | null, stdout: Buffer, stderr: Buffer) => {
        if (error) {
          obser.error(error)
        }
        obser.next({
          stdout,
          stderr
        })
      })
    })
  }

  fork(modulePath: string, args?: string[], options?: ForkOptions): ChildProcess {
    return fork(modulePath, args, options)
  }

  spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess {
    return spawn(command, args, options)
  }
}
